﻿function openDialog( url, width, height ) {
    var _w = 1160, _h = 630;
    _w = width || _w;
    _h = height || _h;

    var iTop = 20; //获得窗口的垂直位置;
    var iLeft = ( window.screen.availWidth - 10 - _w ) / 2; //获得窗口的水平位置;
    window.open( url, "_blank", "width=" + _w + ",height=" + _h + ",top=" + iTop + ",left=" + iLeft + ",resizable=1,scrollbars=1,fullscreen=0" );
};

function showModuleDialog( url, width, height ) {
    var _w = 900, _h = 650;
    _w = width || _w;
    _h = height || _h;
    window.showModalDialog( url, window, "dialogWidth=" + _w + "px;dialogHeight=" + _h + "px" );
};

function CloseSelf() {
    window.open( '', '_self', '' );
    window.close();
};

function GetParentHref() {
    var parent = GetParentWindow();
    if (parent != null) {
        return parent.location.protocol + '//' + parent.location.host + parent.location.pathname;
    }
};

function GetParentWindow() {
    var opener = window.opener;
    if (!opener) {
        //for IE window.opener=undefined
        opener = window.dialogArguments;
    }
    if (!opener) {
        opener = window.parent;
    }

    return opener;
};


//关闭本页面并刷新父页面
function RefreshParentAndCloseSelf() {
    var opener = GetParentWindow();
    if (typeof opener.location.href == 'string') {
        opener.location.href = GetParentHref();
    }
    window.open('', '_self', '');
    window.close();
};



function DateDiff(beginTime, endTime, excludeWeekend, holidays) {
    /// <summary>计算两个时间相差的天数</summary>
    /// <param name="beginTime" type="string">开始时间[yyyy-MM-dd]</param>
    /// <param name="endTime" type="string">结束时间[yyyy-MM-dd]</param>
    /// <param name="excludeWeekend" type="bool">排除周末</param>
    /// <param name="holidays" type="Array">节假日列表</param>
    /// <returns type="int" />

    var dateSplit, _sDate, _begin, _end, Days;
    dateSplit = beginTime.split("-");
    _sDate = dateSplit[0] + '/' + dateSplit[1] + '/' + dateSplit[2];
    _begin = new Date(_sDate);
    dateSplit = endTime.split("-");
    _end = new Date(dateSplit[0] + '/' + dateSplit[1] + '/' + dateSplit[2]);
    Days = parseInt((_end - _begin) / 1000 / 60 / 60 / 24);

    if (Days >= 0) {

        var dayAllLength = Days + 1;

        if (!excludeWeekend) return dayAllLength;

        var weekendCount = 0, weekend;
        var holidayCount = 0, workdayCount = 0;

        for (var i = 1; i <= dayAllLength; i++) {
            weekend = new Date(_sDate).getDay();
            if (weekend == 0 || weekend == 6) {
                weekendCount++;
            }

            var _day = new Date(_sDate).valueOf();

            //后面一天
            _day = _day + (24 * 60 * 60 * 1000);

            _day = new Date(_day);

            _sDate = _day.getFullYear() + '/' + (_day.getMonth() + 1) + '/' + _day.getDate();
        }

        for (var i = 0; i < holidays.length; i++) {
            if (holidays[i].Type == 0) {
                workdayCount++;
            } else {
                holidayCount++;
            }
        }

        return dayAllLength - weekendCount - holidayCount + workdayCount;
    }

    return -1;

};

function isWeekend(day, holidays) {
    var dateSplit = day.split("-");
    var _sDate = dateSplit[0] + '/' + dateSplit[1] + '/' + dateSplit[2];
    var date = new Date(_sDate);
    var weekend = date.getDay();

    var isWeekend = weekend == 0 || weekend == 6;

    for (var i = 0; i < holidays.length; i++) {
        if (holidays[i].Term.getTime() == date.getTime()) {
            if (holidays[i].Type == 0) return false;
        }
    }
    return isWeekend;
};

function isHoliday(day, holidays) {
    var dateSplit = day.split("-");
    var _sDate = dateSplit[0] + '/' + dateSplit[1] + '/' + dateSplit[2];
    var date = new Date(_sDate);

    for (var i = 0; i < holidays.length; i++) {
        if (holidays[i].Term.getTime() == date.getTime()) {
            return holidays[i].Type == 1 || holidays[i].Type == 2;
        }
    }
};

//开始时间小于结束时间的检测
//计算得到总长度和结算长度
function CheckDateGroup(group) {

    var calendars = $('[data-calendar-group="' + group + '"]');

    var beginTime = calendars.filter('[data-calendar-role="begin"]').val(),
        endTime = calendars.filter('[data-calendar-role="end"]').val();

    var beginLengthSelect = $('#LeaveBeginLength'),
        endLengthSelect = $('#LeaveEndLength');

    if (beginTime != "" && endTime != "") {

        //开始时间=结束时间时，要限定结束长度的选择
        if ($.trim(beginTime) == $.trim(endTime)) {
            var beginLength = beginLengthSelect.val();
            endLengthSelect.val(beginLength).attr('disabled', 'disabled');
        } else {
            endLengthSelect.removeAttr('disabled');
        }

        var allLength = DateDiff(beginTime, endTime, false);

        var isWorkingDays = true;//$('#txtVacationDayType').val() == "" || $('#txtVacationDayType').val() == "工作日";

        var holidays = [];//GetCaledarsFromTo(beginTime, endTime);
        var settlementLength = DateDiff(beginTime, endTime, isWorkingDays, holidays);

        //工作日半天假期
        if (+beginLengthSelect.val() == 4) {
            allLength -= 0.5;
            if (!isWorkingDays) {
                settlementLength -= 0.5;
            } else if (!isWeekend(beginTime, holidays) && !isHoliday(beginTime, holidays)) {
                settlementLength -= 0.5;
            }
        }

        //工作日半天假期
        if (+endLengthSelect.val() == 4) {
            if (!endLengthSelect.is(':disabled')) {
                allLength -= 0.5;
                if (!isWorkingDays) {
                    settlementLength -= 0.5;
                } else if (!isWeekend(endTime, holidays) && !isHoliday(beginTime, holidays)) {
                    settlementLength -= 0.5;
                }
            }
        }

        $('#SettlementLength').val(settlementLength);
        $('#hfSettlementLength').val(settlementLength * 8);
        $('#TotalTimeSpan').val(allLength * 8);
    }
};

/*
 * 必填项检查
 */
function requiredValidation( container ) {

    var errorMsg = "",
        requires = container.find( 'span[data-validate]' );

    requires.each( function () {

        var span = $( this );

        var input = $( span ).parents( '.parameter_name' ).next( '.parameter_input' ).find( 'input,select,textare' );

        if ( input && input.length ) {

            var type = input.attr( 'type' ),
                error = span.attr( 'data-validate' );

            if ( type == "radio" ) {
                var groupName = input.attr( 'name' );
                if ( container.find( 'input[type="radio"][name="' + groupName + '"]:checked' ).length == 0 ) {
                    errorMsg += error + "\r";
                }
            } else if ( input.val() == "" || input.val() == null ) {
                errorMsg += error + "\r";
            }
        }

    });

    if ( errorMsg != "" ) {
        alert( errorMsg );
    }

    return errorMsg == "";
};